package com.zheng.mall.controller;

import com.zheng.mall.common.api.CommonResult;
import com.zheng.mall.common.constant.AuthConstant;
import com.zheng.mall.dto.Oauth2TokenDto;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Map;

/**
 * 自定义Oauth2获取令牌接口
 */
@RestController
@Api(tags = "AuthController", description = "认证中心登录认证")
@RequestMapping("/oauth")
public class AuthController {
    @Autowired
    private TokenEndpoint tokenEndpoint;

    @PostMapping("/token")
    public CommonResult<Oauth2TokenDto> postAccessToken(Principal principal,
                                                        @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        OAuth2AccessToken token = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        Oauth2TokenDto tokenInfo = Oauth2TokenDto.builder()
                .token(token.getValue())
                .refreshToken(token.getRefreshToken().getValue())
                .expiresIn(token.getExpiresIn())
                .tokenHead(AuthConstant.JWT_TOKEN_PREFIX).build();
        return CommonResult.success(tokenInfo);
    }
}
